<?php
/**
 *类名：IMwalletPayTrade.php
 *功能  CP服务器端处理IM平台交易返回
 *版本：1.0
 *日期：2017-06-26
'说明：
 */

date_default_timezone_set('Asia/Shanghai');
//ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);

include_once("./mysql.class.php");
include_once("./redis.class.php");
include_once("./logger.php");
include_once("./connConfig.php");
include_once("./httpclient.php");
include_once("./IMpay/config.php");



function recv_post_data() {
	$PostData = file_get_contents('php://input');
	//Config::$logger->info('IMwalletPayTrade',$PostData);exit;
	return $PostData;
}

function record_post_data($PostData) {
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', $PostData);
}

//私钥解密
function private_decrypt($input) {
    $private_key = file_get_contents(__dir__ .'/IMpay/private_key.txt');	
    openssl_private_decrypt(base64_decode($input),$output,$private_key);  
    return $output;  
}  

//公钥验签
function verify($data, $sign, $pubKey)  {
    //转换为openssl格式密钥
    $res = openssl_get_publickey($pubKey);
    //调用openssl内置方法验签，返回bool值
    $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA1);
    //释放资源
    openssl_free_key($res);
    //返回资源是否成功
    return $result;
}

function connect(&$redis, &$mysql) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
        echo("mysql connect error.\n");
		Config::$loggerError->error('IMwalletPayTrade',"mysql connect error.");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
		Config::$loggerError->error('IMwalletPayTrade',"cache redis connect error.");
        exit(0);
    }
}

function process($trade_no,$money,&$payInfArr, &$redis, &$mysql) {
    $row = $mysql->select('applypay','*',array('orderid' => $trade_no));
    if ( count($row) == 0) {
        echo "FAILURE";
		Config::$loggerDebug->debug('IMwalletPayTrade',"FAILURE3");
        exit(0);
    }
    
    $payInfArr = $row[0];
    $uid = (int)$payInfArr['uid'];
    $is_send = (int)$payInfArr['is_send'];
    $gid = (int)$payInfArr['goodsid'];
    //Config::$logger->info('IMwalletPayTrade',json_encode($payInfArr));
    //exit;
	
    //初始化用户redis
	$ret = $redis->initDataRedis($uid);
    if(!$ret) {
        echo("data redis connect error.\n");
		Config::$loggerError->error('IMwalletPayTrade',"data redis connect error.");
        exit(0);
    }
   
    if ($is_send == 1) {
        echo "repead order.";
        echo "FAILURE";
		Config::$loggerDebug->debug('IMwalletPayTrade',"repead order FAILURE.");
        exit(0);
    }

    $mysql->update('applypay',array('is_send' => 1),array('orderid' =>$trade_no) );

    //处理充值，加金币或道具
    $user = $redis->data_redis->hMGet('hu:'.$uid,array('room_card'));
    //Config::$logger->info('IMwalletPayTrade',$user['room_card']);exit;
	
	$goods = $redis->cache_redis->hMGet('hg:'.$gid,array('money','type','propid'));
	$num = $goods['money'];//产品数量
	if($goods['type']==1){//房卡
		$room_card = (int)$user['room_card']+$num;
		$redis->data_redis->hMset('hu:'.$uid,array('money'=>$money,'room_card'=>$room_card));
	}			
	//判断是否存在背包				
	$isExists = $redis->cache_redis->keys('hbackpack:'.$uid.":*");
	if(count($isExists) <= 0){
	//若不存在则添加背包并初始化
		$data = array('uid'=>$uid,'propid'=>(int)$good['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
		$redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],$data);
	}else{
		//若存在则判断是否存在相同道具
		$isExistsProp = $redis->cache_redis->exists('hbackpack:'.$uid.':'.(int)$goods['propid']);
		//存在相同道具,则叠加
		if($isExistsProp){
			$row = $redis->cache_redis->hMget('hbackpack:'.$uid.':'.(int)$goods['propid'],array('propid','count'));
			if($row['propid']==1){//房卡
				$count = 0;
				$count = $row['count']+$num;
			    $redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],array('count'=>$count,'status'=>1));
			}else{//其他道具
							
			     }
		}else{
			//不存在相同道具,则添加记录
			$data = array('uid'=>$uid,'propid'=>(int)$goods['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
			$redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],$data);
		}
	}
}





function do_trade() {
    //$PostData = recv_post_data();
	//if($PostData==''){
		//echo 'dont use get method!!';
		//exit(0);
	//}
	$str = 'heKHmGCHrGhuB4UmVMtIrXyQOYFLFngZSY8+XtaWi5Gg2Npq5Ohz+XQM9G4q0gww6hwYB8aU2ozB02X/D7LwVvXtCqmki+1yEKQA5LJWu+6sXI7HXaBXG79ZTdGQ59okhjKA3oi2q1SOsa8YJhYExOLohbKZPceg/TOhGThAjEk=';
	$publicKey = ibconfig::$publicKey;
	echo $publicKey;
	exit;
	
	
	$dataArr = json_decode($PostData,true);
	$trade_no = private_decrypt($dataArr['orderid']);//订单号
	//Config::$logger->info('IMwalletPayTrade',$trade_no);exit;
	$money = $dataArr['money'];//IM余额
	$redis = new RedisDriver();
    $mysql = new MysqlDriver();
	connect($redis, $mysql);
	process($trade_no,$money,$payInfArr,$redis, $mysql);
	$redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
    echo "SUCCESS";
    exit("SUCCESS");
}

do_trade();

?>
